package avicit.im.lantop.basic.reportmanager.action;

import avicit.cbb.tabledefine.service.CommTableManagerIntfsService;
import avicit.cbb.tabledefine.service.api.CommTableManagerIntfsServiceApi;
import avicit.cbb.techclass.tabledefine.commtablemanager.action.service.api.CommTableManagerServiceApi;
import avicit.cbb.techclass.tabledefine.commtablemanager.service.CommTableManagerService;
import avicit.im.lantop.basic.reportmanager.domain.LantopReportTemplate;
import avicit.im.lantop.basic.reportmanager.service.ReportManagerServices;
import avicit.im.lantop.basic.reportmanager.service.api.ReportManagerServicesApi;
import avicit.im.lantop.basic.reportmanager.util.CreateCPT;
import avicit.platform6.api.session.SessionHelper;
import avicit.platform6.api.sysuser.SysOrgAPI;
import avicit.platform6.api.sysuser.dto.SysOrg;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.JsonHelper;
import avicit.platform6.commons.utils.JsonUtils;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.jdbc.Page;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * <p>
 * 金航数码科技有限责任公司
 * </p>
 * <p>
 * 作者：张欢欢
 * </p>
 * <p>
 * 邮箱：xtcqw369@163.com
 * </p>
 * <p>
 * 创建时间： 2015-11-3 下午2:20:48
 * </p>
 * <p>
 * 类说明：报表管理Controller类
 * </p>
 * <p>
 * 修改记录：
 * </p>
 */
@SuppressWarnings("deprecation")
@Controller
@RequestMapping(value = "im/lantop/basic/ReportManagerController")
public class ReportManagerController {

    @Resource
    private ReportManagerServicesApi services;

    @Resource
    private CommTableManagerIntfsServiceApi commTableManagerIntfsService;

    @Resource
    private CommTableManagerServiceApi commTableManagerService;

    @Autowired
    SysOrgAPI sysOrgAPI;

     private String contextPath = "";

    /**
     * 跳转到报表管理主页面
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/reportmanager")
    public ModelAndView toReportManager(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        String sysId = request.getParameter("sysId");
        String orgId = ThreadContextHelper.getOrgId();
        mav.addObject("sysId", sysId);
        mav.addObject("orgId", orgId);
        mav.addObject("url", "platform/im/lantop/basic/ReportManagerController");
        mav.setViewName("avicit/im/lantop/basic/reportmanager/ReportManager");
        String contextPath = request.getSession().getServletContext().getRealPath("/");
        if (!contextPath.endsWith(File.separator)) {
            contextPath = contextPath + File.separator;
        }
        contextPath = contextPath + "WEB-INF";
        return mav;
    }

    /**
     * 查询是否进行报表打印配置
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     *             ModelAndView
     * @throws
     */
    @RequestMapping(value = "/toFindReportSetField")
    @ResponseBody
    public Map<String,Object> toFindReportSetField(HttpServletRequest request) throws Exception {
        Map<String,Object> map = new HashMap<>();
        String reportId = request.getParameter("templateId");
        String sysId = request.getParameter("sysId");
        String orgId = ThreadContextHelper.getOrgId();
        String tableNames = request.getParameter("tableNames"); // 表名，多个英文逗号分割
        Map<String, String> argsMaps = new HashMap<String, String>();
        argsMaps.put("orgId", orgId);
        argsMaps.put("sysId", sysId);
        argsMaps.put("reportId", reportId);
        argsMaps.put("tableName", tableNames);

        List<Map<String, Object>> setFieldList = services.findReportSetField(argsMaps);
        if (setFieldList.size() > 0) {
            map.put("flag", OpResult.success);
        } else {
            map.put("flag", OpResult.failure);
        }
        return map;
    }

    /**
     * 报表打印接口
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     *             ModelAndView
     * @throws
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/reportview")
    @ResponseBody
    public Map<String,Object> toReportview(HttpServletRequest request) throws Exception {
        Map<String,Object> maps = new HashMap<>();
        // String sysFlag = request.getParameter("sysFlag");
        String reportId = request.getParameter("templateId");
        String sysId = request.getParameter("sysId");
        String type = request.getParameter("type");
        String reportName = URLDecoder.decode(request.getParameter("reportName"), "utf-8");
        String recordIds = request.getParameter("recordIds"); // 一张表
        String tableNames = request.getParameter("tableNames"); // 表名，多个英文逗号分割
        String tableNameIds = request.getParameter("tableNameIds"); // 表名对应的ID，多个英文逗号分割
        String conditions = request.getParameter("conditions"); // 附加打印条件
        conditions = URLDecoder.decode(URLDecoder.decode(conditions, "utf-8"), "utf-8");
        String reportViewType = request.getParameter("reportViewType"); // 打印类型，区别是从哪里打印
        String isPublic = request.getParameter("isPublic"); // 处理档案查询的打印,
        // 多个只打印公共字段的配置
        String viewName = request.getParameter("viewName"); // 处理档案查询的打印，
        // 传递大视图名称
        String archiveTableIds = request.getParameter("archiveTableIds");// 处理档案查询的打印，
        // 处理打印全部
        // 传递tableNames，
        // recordIds
        // 为""
        // 表示全部
        String orgId = ThreadContextHelper.getOrgId();
        String nodeId = request.getParameter("nodeId"); // 数据节点ID
        String[] tableNamesArr = tableNames.split(",");
        String[] tableIdArr = tableNameIds.split(",");
        Map<String, String> argsMaps = new HashMap<String, String>();
        argsMaps.put("sysId", sysId);
        argsMaps.put("reportId", reportId);
        argsMaps.put("tableName", tableNames);
        argsMaps.put("tableId", tableNameIds);
        argsMaps.put("orgId", orgId);
        List<Map<String, Object>> setFieldList = services.findReportSetField(argsMaps);
        boolean f1 = false;// 默认字段未出现
        boolean f2 = false;
        if (tableNamesArr.length == 2) {
            // 判断配置的字段只包含一张表还是两张表
            for (int i = 0; i < setFieldList.size(); i++) {
                String tableName = (String) setFieldList.get(i).get("TABLE_NAME");// 当前字段对应表名
                if (tableNamesArr[0].equals(tableName)) {
                    f1 = true;
                }
                if (tableNamesArr[1].equals(tableName)) {
                    f2 = true;
                }
            }
        }
        // 排序参数
        List<Map<String, Object>> dataSourceList = new ArrayList<Map<String, Object>>();
        if (tableNamesArr.length >= 2) {
            if (f1 && f2) {
                argsMaps.put("tableName", tableNamesArr[1]);
                argsMaps.put("tableId", tableIdArr[1]);
            }
            if (!f1) {
                argsMaps.put("tableName", tableNamesArr[1]);
                argsMaps.put("tableId", tableIdArr[1]);
            }
            if (!f2) {
                argsMaps.put("tableName", tableNamesArr[0]);
                argsMaps.put("tableId", tableIdArr[0]);
            }
        }
        List<Map<String, Object>> sortList = services.findDataSource(argsMaps);
        String sortString = "";
        for (int i = 0; i < sortList.size(); i++) {
            Map<String, Object> sortMap = sortList.get(i);
            String colName = (String) sortMap.get("COL_NAME");
            String sortCode = (String) sortMap.get("SORT_CODE");
            if ("A".equals(sortCode)) {
                sortCode = "ASC";
            } else {
                sortCode = "DESC";
            }
            if (tableNamesArr.length >= 2) {
                if (f1 && f2) {
                    sortString += tableNamesArr[1] + "." + colName + " " + sortCode;
                }
                if (!f1) {
                    sortString += tableNamesArr[1] + "." + colName + " " + sortCode;
                }
                if (!f2) {
                    sortString += tableNamesArr[0] + "." + colName + " " + sortCode;
                }
            } else {
                sortString += tableNames + "." + colName + " " + sortCode;
            }
            if (i != sortList.size() - 1) {
                sortString += ",";
            }
        }

        String orderCols = request.getParameter("tableColsStr");
        JSONArray orderColsJSONArray = JSONArray.parseArray(orderCols);
        Map<String, String> orderColsMapString = new HashMap<String, String>();

        if (null != orderCols && !orderCols.equals("") && !orderCols.equals("null")) {
            sortString = "";
            for (int i = 0; i < orderColsJSONArray.size(); i++) {
                String orderColsJSONString = orderColsJSONArray.get(i).toString();
                orderColsMapString = JsonHelper.getInstance().readValue(orderColsJSONString, Map.class);
                String name = orderColsMapString.get("COL_NAME");
                String sort = orderColsMapString.get("SORT_CODE");
                if (null != sort && !sort.equals("") && !sort.equals("null")) {
                    if (sort.equals("A")) {
                        sort = "ASC";
                    } else if (sort.equals("D")) {
                        sort = "DESC";
                    }
                }
                if (tableNamesArr.length > 1) {
                    sortString += tableNamesArr[0] + "." + name + " " + sort;
                } else {
                    sortString += tableNames + "." + name + " " + sort;
                }
                if (i != orderColsJSONArray.size() - 1) {
                    sortString += ",";
                }
            }
        }

        if (null != sortString && !"".equals(sortString)) {
            Map<String, Object> dataSourceMap = new HashMap<String, Object>();
            dataSourceMap.put("SORT_EXPRESSION", sortString);
            dataSourceList.add(dataSourceMap);
        }
        StringBuffer sql = new StringBuffer();
        if (tableNamesArr.length > 1) {// 由于单张表SQL排序问题，所以区分一张表还是两张表
            sql.append("SELECT  ");
        } else {
            sql.append("SELECT * FROM (SELECT  ");
        }

        boolean isCountType = false;
        // 获得报表配置
        List<Map<String, Object>> list = services.findLantopReportConfigByTemplateId(reportId);
        String reoprtConfigFlag = "no"; // 当前模板报表配置状态
        int countSize = 0; // 进行统计的个数
        // int isCountSize = 0; // 进行求和统计的个数
        if (list.size() > 0) {
            String tempConfig = ""; // 报表配置集合
            String tempCouType = ""; // 配置集合
            for (int i = 0; i < list.size(); i++) {
                tempConfig = tempConfig + list.get(i).get("CONFIG_TYPE") + ",";
                tempCouType = tempCouType + list.get(i).get("REPORT_COUNT_TYPE") + ",";
                if (list.get(i).get("CONFIG_TYPE").equals("20")) {
                    countSize++;
                    if (list.get(i).get("REPORT_COUNT_TYPE").equals("3")) {
                        // isCountSize++;
                    }
                }
            }
            if (tempConfig.contains("10") && tempConfig.contains("20")) { // 当前模板既配置了分组也配置了统计
                reoprtConfigFlag = "yes";
            } else if (tempConfig.contains("20")) { // 当前模板配置统计
                reoprtConfigFlag = "count";
            } else if (tempConfig.contains("10")) { // 当前模板配置分组
                reoprtConfigFlag = "group";
            }
            if (tempCouType.contains("3")) {
                isCountType = true;
            }
        }
        String[] countCol = null; // 进行统计的字段
        String[] countSql = null; // 统计字段的sql
        String groupSql = " GROUP BY "; // 统计字段的sql
        if ("group".equals(reoprtConfigFlag)) {
            String tempGroupBySql = "";
            // 获取分组字段位置下标
            for (int i = 0; i < list.size(); i++) {
                // 获取报表配置的下标
                int tempIndex = Integer.parseInt((String) list.get(i).get("CONFIG_FIELD_NUM")) - 1;
                Map<String, Object> map = setFieldList.get(tempIndex);
                String fieldName = (String) map.get("FIELD_ENGLISH");
                String tableName = (String) map.get("TABLE_NAME");
                String field = tableName + "." + fieldName;
                if (null == fieldName || fieldName.equals("")) {
                    field = "''";
                }

                tempGroupBySql = tempGroupBySql + field + " || ";
            }
            // 去掉最后一个 ||
            tempGroupBySql = tempGroupBySql.substring(0, tempGroupBySql.lastIndexOf("||")) + " AS GROUPCONDATION,";
            sql.append(" " + tempGroupBySql);
        } else if ("count".equals(reoprtConfigFlag) || "yes".equals(reoprtConfigFlag)) {
            Integer[] tempIndexArr = null; // 配置统计下标
            if (!isCountType) { // 没有进行求和
                tempIndexArr = new Integer[countSize];
                countCol = new String[countSize];
                countSql = new String[countSize];
                int tempCountIndex = 0; // 配置为统计的下标
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).get("CONFIG_TYPE").equals("20")) {
                        // 获取报表配置的下标
                        int tempIndex = Integer.parseInt((String) list.get(i).get("CONFIG_FIELD_NUM")) - 1;
                        tempIndexArr[tempCountIndex] = tempIndex;
                        Map<String, Object> mapc = setFieldList.get(tempIndex);
                        String fieldNamec = (String) mapc.get("FIELD_ENGLISH");
                        String tableNamec = (String) mapc.get("TABLE_NAME");
                        String fieldc = tableNamec + "." + fieldNamec;
                        if (null == fieldNamec || fieldNamec.equals("")) {
                            fieldc = "''";
                        }
                        // 获取统计类型
                        String tempCountType = (String) list.get(i).get("REPORT_COUNT_TYPE");
                        if (tempIndex == 0) {
                            countCol[tempCountIndex] = fieldc + ",";
                            if ("1".equals(tempCountType)) { // 最大值
                                countSql[tempCountIndex] = "MAX( " + fieldc + "),";
                            } else if ("2".equals(tempCountType)) { // 最小值
                                countSql[tempCountIndex] = "MIM( " + fieldc + "),";
                            } else if ("4".equals(tempCountType)) { // 平均值
                                countSql[tempCountIndex] = "AVG( " + fieldc + "),";
                            } else if ("5".equals(tempCountType)) { // 区间范围
                                String tempCountSymbol = (String) list.get(i).get("REPORT_COUNT_SYMBOL");
                                if ("".equals(tempCountSymbol) || tempCountSymbol == null) {
                                    countSql[tempCountIndex] = "MIN(" + fieldc + ") || '      ' ||  MAX(" + fieldc + "),";
                                } else {
                                    countSql[tempCountIndex] = "MIN(" + fieldc + ") || '  " + tempCountSymbol + "  ' ||  MAX(" + fieldc + "),";
                                }
                            }
                        } else {
                            countCol[tempCountIndex] = ", " + fieldc;
                            if ("1".equals(tempCountType)) { // 最大值
                                countSql[tempCountIndex] = ",MAX( " + fieldc + ")";
                            } else if ("2".equals(tempCountType)) { // 最小值
                                countSql[tempCountIndex] = ",MIM( " + fieldc + ")";
                            } else if ("4".equals(tempCountType)) { // 平均值
                                countSql[tempCountIndex] = ",AVG( " + fieldc + ")";
                            } else if ("5".equals(tempCountType)) { // 区间范围
                                String tempCountSymbol = (String) list.get(i).get("REPORT_COUNT_SYMBOL");
                                if ("".equals(tempCountSymbol) || tempCountSymbol == null) {
                                    countSql[tempCountIndex] = ",MIN(" + fieldc + ") || '     ' ||  MAX(" + fieldc + ")";
                                } else {
                                    countSql[tempCountIndex] = ",MIN(" + fieldc + ") || '  " + tempCountSymbol + "  ' ||  MAX(" + fieldc + ")";
                                }
                            }
                        }
                        tempCountIndex++;
                    }
                }
                Integer[] fieldSet = new Integer[setFieldList.size()];
                for (int j = 0; j < setFieldList.size(); j++) {
                    fieldSet[j] = j;
                }
                Collection<Integer> co = comptoInteger(tempIndexArr, fieldSet);
                for (Integer integer : co) {
                    Map<String, Object> mapg = setFieldList.get(integer);
                    String fieldNameg = (String) mapg.get("FIELD_ENGLISH");
                    String tableNameg = (String) mapg.get("TABLE_NAME");
                    String fieldg = tableNameg + "." + fieldNameg;
                    if (null == fieldNameg || fieldNameg.equals("")) {
                        fieldg = "''";
                    }
                    groupSql = groupSql + fieldg + ",";
                }
                // 去掉最后一个 ","
                groupSql = groupSql.substring(0, groupSql.lastIndexOf(",")) + " ";
            } else { // 有求和统计
                if ("yes".equals(reoprtConfigFlag)) {
                    // 获取分组字段位置下标
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).get("CONFIG_TYPE").equals("10")) {
                            // 获取报表配置的下标
                            int tempIndex = Integer.parseInt((String) list.get(i).get("CONFIG_FIELD_NUM")) - 1;
                            Map<String, Object> map = setFieldList.get(tempIndex);
                            String fieldName = (String) map.get("FIELD_ENGLISH");
                            String tableName = (String) map.get("TABLE_NAME");
                            String field = tableName + "." + fieldName;
                            if (null == fieldName || fieldName.equals("")) {
                                field = "''";
                            }
                            groupSql = groupSql + field + ",";
                        }
                    }
                    // 去掉最后一个 ","
                    groupSql = groupSql.substring(0, groupSql.lastIndexOf(",")) + " ";
                }
            }
        } else if ("no".equals(reoprtConfigFlag)) {
            String reportRealName = services.getReportRealNameById(reportId);
            if (null != reportRealName && !"".equals(reportRealName) && !"null".equals(reportRealName)) {
                String[] reportRealNameArr = reportRealName.split("group");
                // 如果CPT文件存在group关键字，拼接GROUPCONDATION字段
                if (reportRealNameArr.length > 1) {
                    String groupCondation = reportRealNameArr[reportRealNameArr.length - 1];
                    if (null != groupCondation && !"".equals(groupCondation) && !"null".equals(groupCondation)) {
                        groupCondation = groupCondation.replace(".cpt", "");
                        String[] groupCondationArr = groupCondation.split(";");
                        String sqlCondation = "";
                        if (tableNamesArr.length > 1) { // 多张表
                            for (int i = 0; i < groupCondationArr.length; i++) {
                                String condation = groupCondationArr[i];
                                sqlCondation = sqlCondation + tableNamesArr[0] + "." + condation + "||";
                            }
                        } else { // 一张表
                            for (int i = 0; i < groupCondationArr.length; i++) {
                                String condation = groupCondationArr[i];
                                sqlCondation = sqlCondation + condation + "||";
                            }
                        }
                        if (sqlCondation != "") {
                            sqlCondation = sqlCondation.substring(0, sqlCondation.length() - 2);
                            sqlCondation = sqlCondation + " AS GROUPCONDATION,";
                            sql.append(sqlCondation);
                        }
                    }
                }
            }
        }

        for (Map<String, Object> map : setFieldList) {
            String fieldName = (String) map.get("FIELD_ENGLISH");
            String tableName = (String) map.get("TABLE_NAME");
            long order = Long.parseLong(map.get("FIELD_SERIAL").toString());
            if (null == fieldName || fieldName.equals("")) {
                sql.append("'' AS " + fieldName + "_" + order + ",");
                continue;
            }
            String tableId = "";
            if (tableNamesArr.length > 1) { // 多张表
                for (int i = 0; i < tableNamesArr.length; i++) {
                    if (tableNamesArr[i].equals(tableName)) {
                        tableId = tableIdArr[i];
                    }
                }
            } else { // 一张表
                tableId = tableNameIds;
            }
            String field = "";
            if ("".equals(isPublic)) {
                // 根据表ID获取表字段信息，将通用代码列转换
                List<Map<String, Object>> colList = commTableManagerIntfsService.getCbbTableAndColumnsByTabIdByIntfs(tableId);
                if (colList.size() > 0) {
                    String coLId = "";
                    for (int i = 0; i < colList.size(); i++) {
                        Map<String, Object> colMap = colList.get(i);
                        String colName = (String) colMap.get("COL_NAME");
                        if (colName.equals(fieldName)) {
                            if ("1".equals((String) colMap.get("COL_DROPDOWN_TYPE")) || "2".equals((String) colMap.get("COL_DROPDOWN_TYPE"))) {
                                coLId = (String) colMap.get("COL_ID");
                                // 字段设置的通用代码集合
                                List<Object[]> lookupList = commTableManagerService.getLookupCodeByColumnId(coLId);
                                if (lookupList.size() > 0) {
                                    String sqlDecodeParam = "";
                                    for (Object[] obj : lookupList) {
                                        sqlDecodeParam = sqlDecodeParam + "," + "'" + obj[1] + "','" + obj[0] + "'";
                                    }
                                    if (!isCountType) {
                                        field = " DECODE(" + tableName + "." + fieldName + sqlDecodeParam + ")  AS " + fieldName + "_" + order + ",";
                                    } else {
                                        field = " COUNT(DECODE(" + tableName + "." + fieldName + sqlDecodeParam + "))  AS " + fieldName + "_" + order + ",";
                                    }
                                } else {
                                    if (!isCountType) {
                                        field = " " + tableName + "." + fieldName + " AS " + fieldName + "_" + order + ",";
                                    } else {
                                        field = " COUNT(" + tableName + "." + fieldName + ") AS " + fieldName + "_" + order + ",";
                                    }
                                }
                            } else {
                                if (!isCountType) {
                                    field = " " + tableName + "." + fieldName + " AS " + fieldName + "_" + order + ",";
                                } else {
                                    field = " COUNT(" + tableName + "." + fieldName + ") AS " + fieldName + "_" + order + ",";
                                }
                            }
                        }
                    }
                }
            } else {
                if (!isCountType) {
                    field = " " + fieldName + ",";
                } else {
                    field = " COUNT(" + fieldName + "),";
                }
            }
            sql.append(field);
        }
        sql = new StringBuffer(sql.substring(0, sql.length() - 1));
        String[] tableNameArray = tableNames.split(",");
        if ("".equals(isPublic)) {
            if ("1".equals(reportViewType)) {
                // 在管理界面直接打印
                if (dataSourceList.size() > 0) {
                    sql.append("FROM " + dataSourceList.get(0).get("SOURCE_TABLE"));
                    sql.append(" WHERE 1 = 1");
                    String condtion = dataSourceList.get(0).get("CONDITION_EXPRESSION") == null ? "" : dataSourceList.get(0).get("CONDITION_EXPRESSION").toString();
                    String sort = dataSourceList.get(0).get("SORT_EXPRESSION") == null ? "" : dataSourceList.get(0).get("SORT_EXPRESSION").toString();
                    if (!"".equals(condtion)) {
                        String[] codtions = condtion.split(",");
                        for (String cod : codtions) {
                            sql.append(" AND " + cod);
                        }
                    }
                    if (!"count".equals(reoprtConfigFlag) && !"yes".equals(reoprtConfigFlag)) {
                        if (!"".equals(sort)) {
                            sql.append(" ORDER BY " + sort);
                        }
                    }
                }
            } else {
                // 是在打印接口中调用打印按钮
                // 认为直接就是从前台传递过来的参数
                if ("2".equals(reportViewType)) {
                    // 打印一维码
                    sql.append(", LANTOP_BAR_CODE_RECORD.BAR_CODE_REAL_VALUE ");
                    sql.append(" FROM " + tableNames + " INNER JOIN LANTOP_BAR_CODE_RECORD ON " + tableNames + ".ID = LANTOP_BAR_CODE_RECORD.RECORD_ID ");
                } else if ("3".equals(reportViewType)) {
                    List<Map<String, Object>> ruleMap = services.findRuleInfoByTableId(tableNameIds, nodeId);
                    if (ruleMap == null || ruleMap.size() < 1) {
                        // 条码规则
                        ruleMap = services.findRuleInfoByTableId(tableNameIds);
                    }

                    if (ruleMap != null && ruleMap.size() > 0) {
                        String codeStr = "";
                        String condEn = (String) ruleMap.get(0).get("COND_EXPRESS_EN");
                        String tableName = (String) ruleMap.get(0).get("ARCHIVE_TABLE_NAME");
                        if (null != condEn) {
                            Map<String, Object> paramsMap = new HashMap<String, Object>();
                            try {
                                paramsMap = JsonHelper.getInstance().readValue(condEn, new TypeReference<HashMap<String, Object>>() {
                                });
                            } catch (Exception e) {
                                paramsMap.clear();
                            }

                            String colfield = "colfield";
                            String text = "text";
                            int i = 0;
                            while (true) {
                                String field = (String) paramsMap.get(colfield);
                                if (null == field || "".equals(field) || "null".equals(field)) {
                                    break;
                                }
                                i++;
                                text = text + i;
                                String text1 = (String) paramsMap.get(text);
                                codeStr += tableName + "." + field + "||";
                                if (null != text1) {
                                    codeStr += "'" + text1 + "'||";
                                }
                                colfield = "colfield";
                                text = "text";
                                colfield = colfield + i;
                            }
                            if (!"".equals(codeStr)) {
                                codeStr = codeStr.substring(0, codeStr.length() - "||".length());
                            }
                        }
                        if (!"".equals(codeStr)) {
                            sql.append(", " + codeStr);
                        }
                        sql.append(" FROM " + tableNames);
                        sql.append(" WHERE 1 = 1 ");
                    }
                } else {
                    if (tableNameArray.length >= 2) { // 案卷级盒级数据源
                        if (f1 && f2) {
                            // 拼接‘案卷级ID’列用户报表分组
                            sql.append(" FROM " + tableNameArray[0]);
                            sql.append(" LEFT JOIN  " + tableNameArray[1] + " ON " + tableNameArray[1] + ".PARENT_ID = " + tableNameArray[0] + ".ID");
                        } else if (!f1) {
                            sql.append(" FROM " + tableNameArray[1]);
                        } else if (!f2) {
                            sql.append(" FROM " + tableNameArray[0]);
                        }
                    } else { // 文件级数据源
                        sql.append(" FROM " + tableNames);
                    }
                    sql.append(" WHERE 1 = 1");
                    if (tableNameArray.length >= 2) {
                        if (f1 && f2) {
                            // 案卷数据下的文件数据
                            sql.append(" AND " + tableNameArray[1] + ".PARENT_ID IS NOT NULL \n");
                        }
                    }
                    // nodeId过滤
                    if (null != nodeId && !"".equals(nodeId) && !"null".equals(nodeId)) {
                        if (tableNameArray.length >= 2) {
                            sql.append(" AND " + tableNameArray[0] + ".NODE_ID = '" + nodeId + "'");
                        } else {
                            sql.append(" AND " + tableNames + ".NODE_ID = '" + nodeId + "'");
                        }
                    }
                    /*
                     * // 添加权限过滤 String tableIdParam = ""; if (tableIdArr.length > 1) { tableIdParam = tableIdArr[0]; } else { tableIdParam = tableNameIds; } String userSecretLevel
                     * = avicit.platform6.api.session.SessionHelper.getLoginSysUser(request).getSecretLevel(); Map<String, Object> authMap = new HashMap<String, Object>();
                     * authMap.put("userSecretLevel", userSecretLevel); authMap.put("isEnable", "Y"); Map<String, String> wjjAuthMap = userAuthIntfsService
                     * .getUserAuthDatasByIntfs(SessionHelper.getCurrentOrgId(), SessionHelper.getCurrentDeptId(), sysId, "3", SessionHelper.getLoginSysUserId(),
                     * "LANTOP_AUTH_SERVER_USERSET", nodeId, tableIdParam, "", authMap); String wjjAuthSql = wjjAuthMap.get("SQL"); if (null != wjjAuthSql && !"".equals(wjjAuthSql)
                     * && !"null".equals(wjjAuthSql)) { sql.append(wjjAuthSql + ")"); }
                     */
                }
                if ("".equals(recordIds)) {
                    // 则导出全部，不做处理
                    if (tableNameArray.length >= 2 && !f2) {
                    	if(conditions.indexOf(tableNameArray[1]) == -1){
                    		if (conditions.length() > 0) {
                                sql.append(" AND " + conditions);
                            }
                    	}
                    }else{
                    	if (conditions.length() > 0) {
                            sql.append(" AND " + conditions);
                        }
                    }
                    
                } else {
                    // 部分导出
                    if (tableNameArray.length >= 2) {
                        // 两张表，则添加关系
                        String ids = getRecordIdsForIn(recordIds);
                        if (ids.length() > 0) {
                            sql.append(" AND " + tableNameArray[0] + ".ID IN(" + ids + ")");
                        }
                        if(f2){
                        	if (conditions.length() > 0) {
                                sql.append(" AND " + conditions);
                            }
                        }else{
                        	if(conditions.indexOf(tableNameArray[1]) == -1){
                        		if (conditions.length() > 0) {
                                    sql.append(" AND " + conditions);
                                }
                        	}
                        }
                    } else {
                        // 一张表
                        String ids = getRecordIdsForIn(recordIds);
                        if (ids.length() > 0) {
                            sql.append(" AND " + tableNames + ".ID IN(" + ids + ")");
                        }
                        // SanXiaFiles delete by zhaoxiaolong 一张表时，不需要查当前数据的parentId
                        /*if (conditions.length() > 0) {
                            sql.append(" AND " + conditions);
                        }*/
                    }
                }
                if (dataSourceList.size() > 0) {
                    String condtion = dataSourceList.get(0).get("CONDITION_EXPRESSION") == null ? "" : dataSourceList.get(0).get("CONDITION_EXPRESSION").toString();
                    String sort = dataSourceList.get(0).get("SORT_EXPRESSION") == null ? "" : dataSourceList.get(0).get("SORT_EXPRESSION").toString();
                    if (!"".equals(condtion)) {
                        String[] codtions = condtion.split(",");
                        for (String cod : codtions) {
                            sql.append(" AND " + cod);
                        }
                    }
                    if (!"count".equals(reoprtConfigFlag) && !"yes".equals(reoprtConfigFlag)) {
                        if (!"".equals(sort)) {
                            sql.append(" ORDER BY " + sort);
                        }
                    }
                }
            }
        } else {
            // 处理档案查询中的报表打印，这里从大视图取出数据
            sql.append(" FROM " + viewName);
            sql.append(" WHERE 1 = 1");
            // 区分打印全部还是仅选中
            if ("".equals(recordIds)) {
                // 打印全部
                String ids = getRecordIdsForIn(archiveTableIds);
                if (ids.length() > 0) {
                    sql.append(" AND " + viewName + ".ARCHIVE_TABLE_ID IN(" + ids + ")");
                }
            } else {
                // 打印仅选中记录
                String ids = getRecordIdsForIn(recordIds);
                if (ids.length() > 0) {
                    sql.append(" AND " + viewName + ".LANTOP_RCD_ID IN(" + ids + ")");
                }
            }
            if (conditions.length() > 0) {
                sql.append(" AND " + conditions);
            }
        }
        if (tableNamesArr.length == 1) {// 由于单张表SQL排序问题，所以区分一张表还是两张表
            sql.append(" )WHERE ROWNUM <= 999999999999");
        }
        if ("count".equals(reoprtConfigFlag) || "yes".equals(reoprtConfigFlag)) {
            // 添加分组字段
            if (tableNamesArr.length == 1) {
                if (!(isCountType && "count".equals(reoprtConfigFlag))) {
                    sql.insert(sql.lastIndexOf(")WHERE ROWNUM"), groupSql);
                }
            } else if (tableNamesArr.length == 2) {
                if (!(isCountType && "count".equals(reoprtConfigFlag))) {
                    sql.append(groupSql);
                }
            }
            if (!isCountType) {
                for (int i = 0; i < countCol.length; i++) {
                    int startIndex = sql.indexOf(countCol[i]);
                    int endIndex = sql.indexOf(countCol[i]) + countCol[i].length();
                    // 替换统计字段
                    sql.replace(startIndex, endIndex, countSql[i]);
                }
            }
        }
        maps.put("sql", sql.toString());
        maps.put("type", type);
        maps.put("reportName", reportName);
        //mav.addObject("reportName", URLDecoder.decode(URLDecoder.decode(reportName, "utf-8"), "utf-8"));
        // 测试插入打印报表临时数据表,返回临时表id,跳转页面时只传递id进行报表打印效果.
        LantopReportTemplate temp = new LantopReportTemplate();
        temp.setReportName(URLDecoder.decode(URLDecoder.decode(reportName, "utf-8"), "utf-8"));//
        temp.setCondition(sql.toString());
        String id = this.services.saveReportTemplate(temp);
        maps.put("tempId", id);
        return maps;
    }

    /**
     * 求两个数组差集
     *
     * @param Integer[]
     * @return Collection
     * @throws
     */
    private static Collection<Integer> comptoInteger(Integer[] arr, Integer[] arr2) {
        Set<Integer> result = new HashSet<Integer>();
        List<Integer> _a = Arrays.asList(arr);
        List<Integer> _b = Arrays.asList(arr2);
        // 创建集合
        ArrayList<Integer> realA = new ArrayList<Integer>(_a);
        ArrayList<Integer> realB = new ArrayList<Integer>(_b);
        // 求交集
        realA.retainAll(realB);
        // 求全集
        result.addAll(_a);
        result.addAll(_b);
        // 求差集：结果
        Collection<Integer> aa = new ArrayList<Integer>(realA);
        Collection<Integer> bb = new ArrayList<Integer>(result);
        bb.removeAll(aa);
        return bb;
    }

    /**
     * 辅助方法，将用","隔开的ID，组合成使用IN可以直接使用的字符串
     *
     * @param recordIds
     * @return String
     * @throws
     */
    private String getRecordIdsForIn(String recordIds) {
        String ids = "";
        String[] reCordIdsArray = recordIds.split(",");
        for (String id : reCordIdsArray) {
            ids = ids + "'" + id + "'" + ",";
        }
        if (ids.length() > 0) {
            ids = ids.substring(0, ids.length() - 1);
        }
        return ids;
    }

    /**
     * 获取报表树结构
     *
     * @param id
     *            节点ID
     * @param level
     *            层级
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/gettree/{level}/{rtype}")
    @ResponseBody
    public Map<String,Object> getTree(@RequestParam(required = false)
                                        String id, @PathVariable(value = "level")
                                        int level, @PathVariable(value = "rtype")
                                        String rtype, HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        if (id == null) {
            id = "-1";
        } else {
            level = 1;
        }
        String sysId = request.getParameter("sysId");
        String contextPath = request.getSession().getServletContext().getRealPath("/");
        if (!contextPath.endsWith(File.separator)) {
            contextPath = contextPath + File.separator;
        }
        contextPath = contextPath + "WEB-INF";
        String orgIdentity = avicit.platform6.api.session.SessionHelper.getCurrentOrgIdentity();
        String orgId = ThreadContextHelper.getOrgId();
        if (null != rtype && rtype.equals("root")) {
            orgIdentity = "ORG_ROOT";
            orgId = "ORG_ROOT";
        }
        List<TreeNode> node = services.getTreeExerciseByParentId(id, orgId, orgIdentity, level, contextPath);
        if (node == null || node.size() == 0) {
            if (rtype.equals("root")) {// 根组织树加载
                if (ThreadContextHelper.getOrgId().equals("ORG_ROOT")) {// 当中在根组织下
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("sysId", sysId);
                    param.put("id", "");
                    param.put("_parentId", "-1");
                    param.put("text", "报表管理");
                    param.put("reportType", "0");
                    services.insertIntoLantopReportTree(param);
                    node = services.getTreeExerciseByParentId(id, orgId, orgIdentity, level, contextPath);
                }
            } else {// 自组织树加载
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("sysId", sysId);
                param.put("id", "");
                param.put("_parentId", "-1");
                param.put("text", "报表管理");
                param.put("reportType", "0");
                services.insertIntoLantopReportTree(param);
                node = services.getTreeExerciseByParentId(id, orgId, orgIdentity, level, contextPath);
            }
        }
        map.put("data", node);
        return map;
    }

    /**
     * 保存报表以及模板配置字段信息
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/save")
    public ModelAndView toSave(HttpServletRequest request) {

        ModelAndView mav = new ModelAndView();
        mav.setViewName(null);

        String params = request.getParameter("param");
        Map<String, Object> paramsMap = null;

        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
        }

        if (null != paramsMap) {

            boolean success = services.saveLantopReport(paramsMap);
            success = true;
            if (success) {
                String sql = createSQLByFields(paramsMap);
                mav.addObject("sql", sql);
                mav.addObject("flag", OpResult.success);

            } else {
                mav.addObject("flag", OpResult.failure);
            }
        } else {
            mav.addObject("flag", OpResult.failure);
        }

        return mav;
    }

    /**
     * 根据配置字段信息生成SQL语句
     *
     * @param paramsMap
     *            参数集合
     * @return String SQL语句
     * @throws
     */
    @SuppressWarnings("unchecked")
    private String createSQLByFields(Map<String, Object> paramsMap) {
        // 获得报表配置
        List<Map<String, Object>> list = services.findLantopReportConfigByTemplateId((String) paramsMap.get("templateId"));
        String reoprtConfigFlag = "no"; // 当前模板报表配置状态
        if (list.size() > 0) {
            String tempConfig = ""; // 报表配置集合
            for (int i = 0; i < list.size(); i++) {
                tempConfig = tempConfig + list.get(i).get("CONFIG_TYPE") + ",";
            }
            if (tempConfig.contains("10") && tempConfig.contains("20")) { // 当前模板既配置了分组也配置了统计
                reoprtConfigFlag = "yes";
            } else if (tempConfig.contains("20")) { // 当前模板配置统计
                reoprtConfigFlag = "count";
            } else if (tempConfig.contains("10")) { // 当前模板配置分组
                reoprtConfigFlag = "group";
            }
        }

        StringBuffer sql = new StringBuffer();
        sql.append("SELECT ");

        List<String> tableNames = (List<String>) paramsMap.get("tableNames");
        List<Map<String, String>> currFields = (List<Map<String, String>>) paramsMap.get("currFields"); // 实际输出字段

        if ("no".equals(reoprtConfigFlag) || "yes".equals(reoprtConfigFlag)) { // 没有报表模板配置（同时配置了分组和统计暂不处理）
            // 按照多张表生成，如果有多张表，就需要考虑where条件,暂时不考虑where条件
            for (int i = 0; i < currFields.size(); i++) {
                Map<String, String> map = currFields.get(i);
                String fieldName = map.get("COL_NAME");
                String tableName = map.get("TABLE_NAME");
                String field = tableName + "." + fieldName;
                if (null == fieldName || fieldName.equals("")) {
                    field = "''";
                }
                sql.append(" " + field);
                sql.append(",");

            }
            // 去掉最后一个 ,
            sql.replace(sql.length() - 1, sql.length(), "");
            sql.append("\n");
            sql.append("FROM ");
            for (int i = 0; i < tableNames.size(); i++) {
                String tableName = tableNames.get(i);
                sql.append(" " + tableName);
                sql.append(",");
            }
            // 去掉最后一个 ,
            sql.replace(sql.length() - 1, sql.length(), "");
            sql.append("\n");
            sql.append("WHERE 1 = 1");
        } else if ("group".equals(reoprtConfigFlag)) { // 报表模板配置--分组
            String tempGroupBySql = "";
            // 获取分组字段位置下标
            for (int i = 0; i < list.size(); i++) {
                // 获取报表配置的下标
                int tempIndex = Integer.parseInt((String) list.get(i).get("CONFIG_FIELD_NUM")) - 1;
                Map<String, String> map = currFields.get(tempIndex);
                String fieldName = map.get("COL_NAME");
                String tableName = map.get("TABLE_NAME");
                String field = tableName + "." + fieldName;
                if (null == fieldName || fieldName.equals("")) {
                    field = "''";
                }
                tempGroupBySql = tempGroupBySql + field + " || ";
            }
            // 去掉最后一个 ||
            tempGroupBySql = tempGroupBySql.substring(0, tempGroupBySql.lastIndexOf("||")) + " AS GROUPCONDATION,";
            sql.append(" " + tempGroupBySql);
            for (int i = 0; i < currFields.size(); i++) {
                Map<String, String> map = currFields.get(i);
                String fieldName = map.get("COL_NAME");
                String tableName = map.get("TABLE_NAME");
                String field = tableName + "." + fieldName;
                if (null == fieldName || fieldName.equals("")) {
                    field = "''";
                }
                sql.append(" " + field);
                sql.append(",");
            }
            // 去掉最后一个 ,
            sql.replace(sql.length() - 1, sql.length(), "");
            sql.append("\n");
            sql.append("FROM ");
            for (int i = 0; i < tableNames.size(); i++) {
                String tableName = tableNames.get(i);
                sql.append(" " + tableName);
                sql.append(",");
            }
            // 去掉最后一个 ,
            sql.replace(sql.length() - 1, sql.length(), "");
            sql.append("\n");
            sql.append("WHERE 1 = 1");
        } else if ("count".equals(reoprtConfigFlag)) { // 报表模板配置--统计
            for (int i = 0; i < currFields.size(); i++) {
                Map<String, String> map = currFields.get(i);
                String fieldName = map.get("COL_NAME");
                String tableName = map.get("TABLE_NAME");
                String field = tableName + "." + fieldName;
                field = "COUNT (" + field + ")";
                if (null == fieldName || fieldName.equals("")) {
                    field = "''";
                }
                sql.append(" " + field);
                sql.append(",");
            }
            // 去掉最后一个 ,
            sql.replace(sql.length() - 1, sql.length(), "");
            sql.append("\n");
            sql.append("FROM ");
            for (int i = 0; i < tableNames.size(); i++) {
                String tableName = tableNames.get(i);
                sql.append(" " + tableName);
                sql.append(",");
            }
            // 去掉最后一个 ,
            sql.replace(sql.length() - 1, sql.length(), "");
            sql.append("\n");
            sql.append("WHERE 1 = 1");
        }
        return sql.toString();
    }

    /**
     * 删除报表树节点
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/deletereporttree")
    @ResponseBody
    public Map<String,Object> deleteReportTree(HttpServletRequest request) {

        Map<String,Object> map = new HashMap<>();

        String params = request.getParameter("param");
        Map<String, Object> paramsMap = null;

        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
        }

        if (null != paramsMap) {
            boolean success = services.deleteLantopReportTree(paramsMap);
            if (success) {
                map.put("flag", OpResult.success);

            } else {
                map.put("flag", OpResult.failure);
            }
        } else {
            map.put("flag", OpResult.failure);
        }

        return map;

    }

    /**
     * 插入报表树节点
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/insertreporttree")
    @ResponseBody
    public Map<String,Object> insertReportTree(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        String params = request.getParameter("param");
        Map<String, Object> paramsMap = null;
        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
        }
        if (null != paramsMap) {
            boolean success = services.insertIntoLantopReportTree(paramsMap);
            if (success) {
                map.put("flag", OpResult.success);

            } else {
                map.put("flag", OpResult.failure);
            }
        } else {
            map.put("flag", OpResult.failure);
        }
        return map;
    }

    /**
     * 根据type类型，跳转到当前数据库或者是用户自定义页面
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/datasourcetype")
    public ModelAndView toDataSourceType(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        String type = request.getParameter("type");
        String dialogId = request.getParameter("dialogId");
        String sysId = request.getParameter("sysId");
        String parentId = request.getParameter("parentId");

        if ("0".equals(type)) {
            // 当前数据库
            mav.setViewName("avicit/im/lantop/basic/reportmanager/DataBaseSource");
        } else {
            // 用户自定义
            mav.setViewName("avicit/im/lantop/basic/reportmanager/UserCustomDataSource");

        }
        mav.addObject("sysId", sysId);
        mav.addObject("dialogId", dialogId);
        mav.addObject("type", type);
        mav.addObject("parentId", parentId);

        return mav;

    }

    /**
     * 保存用户自定义数据源
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/saveusecustomdatasource")
    @ResponseBody
    public Map<String,Object> toSaveUseCustomDataSource(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();

        String params = request.getParameter("param");
        Map<String, Object> paramsMap = null;

        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
        }

        if (null != paramsMap) {
            boolean success = services.saveUseCustomDataSource(paramsMap);
            if (success) {
                map.put("templateId", paramsMap.get("___templateId"));
                map.put("flag", OpResult.success);

                String reportId = (String) paramsMap.get("___templateId");
                // 根据ReportId 查询，该模板所包含的字段，生成cpt文件
                List<String> columnList = services.findUseCustomDataSourceFields(reportId, paramsMap);

                // 如果columnList没有数据，则生成一个空的
                String contextPath = request.getSession().getServletContext().getRealPath("/");
                if (!contextPath.endsWith(File.separator)) {
                    contextPath = contextPath + File.separator;
                }
                contextPath = contextPath + "WEB-INF";
                CreateCPT ccpt = new CreateCPT(columnList, "${SQL}", contextPath, "lantop");
                String fileName = (String) paramsMap.get("text");
                ccpt.saveCPT(fileName);

            } else {
                map.put("flag", OpResult.failure);

            }

        }

        return map;

    }

    /**
     * 根据模板ID查找报表配置信息
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/findfieldinfosbyreportid")
    @ResponseBody
    public Map<String,Object> toFindFieldInfosByReportid(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();

        String params = request.getParameter("param");

        String pageNo = request.getParameter("page");
        String pageSize = request.getParameter("rows");
        Page<Map<String, Object>> page = new Page<Map<String, Object>>();
        page.setPage(ComUtil.getPageNo(pageNo));
        page.setRows(ComUtil.getPageSize(pageSize));

        Map<String, Object> paramsMap = null;

        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
        }

        if (null != paramsMap) {
            services.findFieldInfosByReportid(paramsMap, page);

            map.put("total", page.getEntityCount());
            map.put("rows", page.getEntities());

        }

        return map;

    }

    /**
     * 根据模板ID删除模板配置信息
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/deletefieldinfosbyid")
    public Map<String,Object> toDeleteFieldInfosByID(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();

        String params = request.getParameter("param");

        Map<String, Object> paramsMap = null;

        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
        }

        if (null != paramsMap) {
            boolean success = services.deleteFieldInfosById(paramsMap);
            if (success) {
                map.put("flag", OpResult.success);
            } else {
                map.put("flag", OpResult.failure);
            }

        }

        return map;

    }

    /**
     * 跳转到当前数据库配置页面
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/databasesourceconfig")
    public ModelAndView toDataBaseSourceConfig(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        String type = request.getParameter("type");
        String dialogId = request.getParameter("dialogId");
        String sysId = request.getParameter("sysId");
        String parentId = request.getParameter("parentId");

        mav.addObject("sysId", sysId);

        mav.addObject("sysId", sysId);
        mav.addObject("dialogId", dialogId);
        mav.addObject("type", type);
        mav.addObject("parentId", parentId);

        mav.setViewName("avicit/im/lantop/basic/reportmanager/DataBaseSourceConfig");

        return mav;
    }

    /**
     * 保存当前数据库配置信息
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/savedatabaseconfig")
    @ResponseBody
    public Map<String,Object> saveDataBaseConfig(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        String params = request.getParameter("param");

        Map<String, Object> paramsMap = null;

        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
        }

        if (null != paramsMap) {
            boolean success = services.saveDataBaseConfigForTable(paramsMap);

            if (success) {
                map.put("templateId", paramsMap.get("___templateId"));
                map.put("flag", OpResult.success);

                String reportId = (String) paramsMap.get("___templateId");

                // 根据ReportId 查询，该模板所包含的字段，生成cpt文件
                List<String> columnList = services.findDataSourceFields(reportId, paramsMap);

                // 如果columnList没有数据，则生成一个空的
                String contextPath = request.getSession().getServletContext().getRealPath("/");
                if (!contextPath.endsWith(File.separator)) {
                    contextPath = contextPath + File.separator;
                }
                contextPath = contextPath + "WEB-INF";
                CreateCPT ccpt = new CreateCPT(columnList, "${SQL}", contextPath, "lantop");
                String fileName = (String) paramsMap.get("text");
                ccpt.saveCPT(fileName);
                // 生成模板

            } else {
                map.put("flag", OpResult.failure);
            }
        }
        return map;
    }

    /**
     * 报表模板上传
     *
     * @param file
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/fileupload")
    public ModelAndView saveCPTFileupload(MultipartFile file, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        String fileName = file.getOriginalFilename();
        String contextPath = request.getSession().getServletContext().getRealPath("/");
        if (!contextPath.endsWith(File.separator)) {
            contextPath = contextPath + File.separator;
        }
        contextPath = contextPath + "WEB-INF";
        String filePath = contextPath + File.separator + "reportlets" + File.separator + fileName;
        String parentId = request.getParameter("_parentId");
        String sysId = request.getParameter("sysId");
        String dialogId = request.getParameter("dialogId");
        mav.addObject("dialogId", dialogId);
        boolean success = true;

        try {
            file.transferTo(new File(filePath));

            String reportName = fileName.substring(0, fileName.lastIndexOf('.'));
            Map<String, String> params = new HashMap<String, String>();
            params.put("sysId", sysId);
            params.put("parentId", parentId);
            params.put("reportName", reportName);

            services.insertIntoLantopReportTreeForUpload(params);

        } catch (IllegalStateException e) {
            success = false;

        } catch (IOException e) {
            success = false;
        }
        if (success) {
            mav.addObject("flag", OpResult.success);
            request.setAttribute("message", "导入成功！");
        } else {
            mav.addObject("flag", OpResult.failure);
            request.setAttribute("message", "导入失败！");
        }

        mav.setViewName("avicit/im/lantop/basic/reportmanager/ReportManagerImport");

        return mav;

    }

    /**
     * 报表模板上传
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     *             ResponseEntity<byte[]>
     * @throws
     */
    @RequestMapping(value = "/filedownload")
    public ResponseEntity<byte[]> cptFiledownLoad(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String fileName = "";
        try {
            fileName = URLDecoder.decode(request.getParameter("reportName"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String contextPath = request.getSession().getServletContext().getRealPath("/");
        if (!contextPath.endsWith(File.separator)) {
            contextPath = contextPath + File.separator;
        }
        contextPath = contextPath + "WEB-INF";
        String path = contextPath + File.separator + "reportlets" + File.separator + fileName;
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();

        // 为了解决中文名称乱码问题
        String downLoadFileName = "";
        try {
            downLoadFileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }

        headers.setContentDispositionFormData("attachment", downLoadFileName);

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ResponseEntity<byte[]> responseEntity = null;

        try {
            responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);

        } catch (IOException e) {

            e.printStackTrace();
        }

        return responseEntity;
    }

    /**
     * 跳转到报表配置界面
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/printreport")
    public ModelAndView toPrintReport(HttpServletRequest request) throws UnsupportedEncodingException {
        ModelAndView mav = new ModelAndView();
        String sysFlag = request.getParameter("sysFlag");
        String openType = request.getParameter("openType");
        String sysId = request.getParameter("sysId"); // 系统标识
        String dialogId = request.getParameter("dialogId"); // 对话框ID
        String tableNames = request.getParameter("tableNames"); // 表名, 如果有多个按照 ,
        // 分隔
        String tableNameIds = request.getParameter("tableNameIds"); // 表ID,
        // 如果有多个按照,
        // 分隔
        // 与tableNames对应
        String ids = request.getParameter("ids"); // 如果有选中的数据,则传递选中数据的ID,如果有多个用,
        // 分隔
        String conditions = request.getParameter("conditions"); // 打印附加条件
        String isPublic = request.getParameter("isPublic"); // 处理档案查询的打印,
        // 多个只打印公共字段的配置
        String viewName = request.getParameter("viewName"); // 处理档案查询的打印，
        // 传递大视图名称
        String archiveTableIds = request.getParameter("archiveTableIds");// 处理档案查询的打印，
        // 处理打印全部
        String reportViewType = request.getParameter("reportViewType"); // 打印类型，
        // 区分一维码
        // ， 二维码
        String tableColsStr = request.getParameter("tableColsStr");
        String nodeId = request.getParameter("nodeId"); // 数据节点ID
        String fileIds = request.getParameter("fileIds");
        if (fileIds==null||fileIds.equals("")){
            fileIds = "";
        }
        String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);
        SysOrg so = sysOrgAPI.getSysOrgBySysOrgId(orgIdentity);
        String orgCode = so.getOrgCode();
        if (null != viewName && !"".equals(viewName) && "LATNOP_DATA_V".equals(viewName.toUpperCase())) {
            viewName = orgCode + "_" + viewName;
        }
        mav.addObject("fileIds",fileIds);
        mav.addObject("sysFlag", sysFlag);
        mav.addObject("openType", openType);
        mav.addObject("nodeId", nodeId);
        mav.addObject("sysId", sysId);
        mav.addObject("dialogId", dialogId);
        mav.addObject("tableNames", tableNames);
        mav.addObject("tableNameIds", tableNameIds);
        mav.addObject("tableColsStr", tableColsStr);
        mav.addObject("ids", ids);
        mav.addObject("conditions", conditions);
        mav.addObject("isPublic", isPublic);
        mav.addObject("viewName", viewName);
        mav.addObject("archiveTableIds", archiveTableIds);
        mav.addObject("reportViewType", reportViewType);
        String tableId = request.getParameter("tableId");
        mav.addObject("tableId", tableId);
        mav.setViewName("avicit/im/lantop/basic/reportmanager/PrintReport");
        return mav;
    }

    /**
     * 遍历树, 查询节点的树信息
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/findtreebytablename")
    @ResponseBody
    public Map<String,Object> findTreeByTableName(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        String params = request.getParameter("param");
        Map<String, Object> paramsMap = null;
        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
            paramsMap.put("orgId", ThreadContextHelper.getOrgId());
            paramsMap.put("orgIdentity", avicit.platform6.api.session.SessionHelper.getCurrentOrgIdentity());
        }
        List<TreeNode> nodeList = services.findTreeByTableName(paramsMap);
        map.put("data", nodeList);
        return map;
    }

    /**
     * 调转到打印配置界面
     *
     * @param request
     * @return
     * @throws Exception
     *             ModelAndView
     * @throws
     */
    @RequestMapping(value = "/printfreportconfig")
    public ModelAndView toPrintfReportConfig(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView();
        String dialogId = request.getParameter("dialogId");
        String outPutFields = request.getParameter("outPutFields");
        String templateId = request.getParameter("templateId");
        String tableNameIds = request.getParameter("tableNameIds");
        String sysId = request.getParameter("sysId");
        String type = request.getParameter("type"); // 用来区别从配置报表的取消按钮直接到报表配置页面，
        // 或者是 从选择报表到配置页面
        outPutFields = URLDecoder.decode(outPutFields, "UTF-8");
        int fieldsCount = outPutFields.split(",").length;
        mav.setViewName("avicit/im/lantop/basic/reportmanager/PrintReportConfig");
        mav.addObject("dialogId", dialogId);
        mav.addObject("outPutFields", outPutFields);
        mav.addObject("templateId", templateId);
        mav.addObject("fieldsCount", fieldsCount);
        mav.addObject("tableNameIds", tableNameIds);
        mav.addObject("sysId", sysId);
        mav.addObject("type", type);
        return mav;
    }

    /**
     * 调转到选择报表界面
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "printfselectreport")
    public ModelAndView toPrintfSelectReport(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        String sysId = request.getParameter("sysId");
        String dialogId = request.getParameter("dialogId");
        String templateId = request.getParameter("templateId");
        String tableNameIds = request.getParameter("tableNameIds");
        String orgId = ThreadContextHelper.getOrgId();

        mav.setViewName("avicit/im/lantop/basic/reportmanager/PrintSelectReport");

        mav.addObject("dialogId", dialogId);
        mav.addObject("sysId", sysId);
        mav.addObject("orgId", orgId);
        mav.addObject("templateId", templateId);
        mav.addObject("tableNameIds", tableNameIds);

        return mav;
    }

    /**
     * 删除已经配置的字段信息
     *
     * @param request
     * @return ModelAndView
     * @throws
     */
    @RequestMapping(value = "/deleteSetField")
    public ModelAndView deleteSetField(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        String params = request.getParameter("param");

        Map<String, Object> paramsMap = null;

        if (null != params && !"".equals(params)) {
            paramsMap = JsonHelper.getInstance().readValue(params, new TypeReference<HashMap<String, Object>>() {
            });
        }

        mav.addObject("flag", OpResult.success);

        if (null != paramsMap) {
            boolean flag = services.deleteSetField(paramsMap);
            if (!flag) {
                mav.addObject("flag", OpResult.failure);
            }
        }
        return mav;
    }

    /**
     * 删除报表关系(各模块应用报表处,删除关系功能)
     * @param request
     * @return
     * @throws Exception ModelAndView
     * @throws
     */
    @RequestMapping("deleteReportRelation")
    @ResponseBody
    public Map<String,Object> deleteReportRelation(HttpServletRequest request) throws Exception {
        Map<String,Object> map = new HashMap<>();
        String reportId = request.getParameter("reportId");
        String tableName = request.getParameter("tableName");
        String orgId = ThreadContextHelper.getOrgId();
        try {
            services.deleteReportRelation(reportId, tableName, orgId);
            map.put("flag", OpResult.success.ordinal());
        } catch (Exception e) {
            map.put("flag", OpResult.failure.ordinal());
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("/toPrintPageJsp")
    public ModelAndView toPrintPageJsp(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView();
        String tempId = request.getParameter("templateId");
        LantopReportTemplate template = this.services.getLantopReportTemplateById(tempId);
        mav.addObject("paramNames", "SQL;;reportlet");
        mav.addObject("paramValues", template.getCondition() + ";;" + template.getReportName());
        mav.setViewName("avicit/im/lantop/basic/reportmanager/printPage");
        return mav;
    }

    @RequestMapping("/toPreviewPrintPageJsp")
    public ModelAndView toPreviewPrintPageJsp(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView();
        String reportlet = request.getParameter("reportlet");
        mav.addObject("paramNames", "SQL;;reportlet");
        mav.addObject("paramValues", "SELECT ' ' FROM DUAL;;" + reportlet);
        mav.setViewName("avicit/im/lantop/basic/reportmanager/printPage");
        return mav;
    }

}
